package org.team4u.demo.fsh.web;


import com.asiainfo.common.util.CollectionUtil;
import com.asiainfo.common.util.ServiceProvider;
import com.asiainfo.common.util.SimpleMap;
import com.asiainfo.common.util.Values;
import com.asiainfo.dao.core.SimpleDao;
import com.asiainfo.sql.builder.Sql;
import com.asiainfo.sql.builder.util.SqlBuilders;
import org.team4u.fhs.server.HttpServerRequest;
import org.team4u.fhs.web.handler.method.annotation.Controller;
import org.team4u.fhs.web.handler.method.annotation.RequestMapping;
import org.team4u.fhs.web.handler.method.annotation.ResponseView;

/**
 * @author Jay Wu
 */
@Controller("/test")
public class TestController {

    private SimpleDao dao = ServiceProvider.getInstance().get(SimpleDao.class);

    @RequestMapping("/mill")
    @ResponseView(success = "raw")
    public Long mill() {
        return System.currentTimeMillis();
    }

    @RequestMapping("/json")
    @ResponseView(success = "json")
    public Object json() {
        return new SimpleMap("x", "1");
    }

    @RequestMapping("/html")
    @ResponseView(success = "beetl:/index.html")
    public void html(HttpServerRequest request) {
        request.setAttribute("name", Values.defaultIfEmpty(request.getParameter("name"), "all"));
        request.setAttribute("list", CollectionUtil.arrayListOf(1, 2, 3));
    }

    @RequestMapping("/db")
    @ResponseView(success = "raw")
    public int db() {
        TestEntity entity = insertEntity();
        Sql sql = SqlBuilders.select(TestEntity.class)
                .where("name", "=", entity.getName())
                .create();
        return dao.count(sql);
    }

    private TestEntity insertEntity() {
        TestEntity entity = new TestEntity();
        entity.setName("x");
        return dao.insert(entity);
    }
}